package com.project.api.sale.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.api.common.ApiResponse;
import com.project.api.common.wxpay.WXPay;
import com.project.api.common.wxpay.WXPayConstants;
import com.project.api.common.wxpay.WXPayUtil;
import com.project.api.sale.dao.*;
import com.project.api.sale.common.Weixin;
import com.project.api.sale.service.OrderService;
import com.project.api.sale.service.ProductService;
import com.project.api.sale.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.util.*;

@Controller
public class HtmlController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final String prefix="wssale";
    @Autowired
    public ProductService productService;
    @Autowired
    public UserService userService;
    @Autowired
    public OrderService orderService;
//    @RequestMapping("/")
//    public ModelAndView Index(Model model,HttpServletRequest request){
//        return HtmlIndex(model,request);
//    }
    @RequestMapping(prefix+"/index.html")
    public ModelAndView HtmlIndex(Model model,HttpServletRequest request){
//        String openid="oclyy1Y4GbNp6QDJU6Si_PuGMCyc";
//        HttpSession session=request.getSession();
//        session.setAttribute("openid",openid);
        List products=productService.getProductLists();
        model.addAttribute("products", products);
        return new ModelAndView("index");
    }
    @RequestMapping(prefix+"/reg.html")
    public ModelAndView HtmlReg(Model model,HttpServletRequest request){
        HttpSession session=request.getSession();
        UserDao userDao=new UserDao();
        Object userId=session.getAttribute("userId");
        if(userId!=null){
           int uid=(int)userId;
           userDao=userService.getUser(uid);
        }
        model.addAttribute("user",userDao);
        return new ModelAndView("reg");
    }
    @RequestMapping(prefix+"/shoppingcart.html")
    public ModelAndView HtmlShoppingcart(Model model,HttpServletRequest request){
        HttpSession session=request.getSession();
        String openid=(String)session.getAttribute("openid");

        int userId= 0;
        try {
            userId = (int)session.getAttribute("userId");
        } catch (NullPointerException e) {
            return new ModelAndView("redirect:/index.html");
        }
        List<BuyCarDao> lists=userService.getBuyCar(userId);
//        List products=productService.getProductLists();
        model.addAttribute("products",lists);
        return new ModelAndView("shoppingcart");
    }
    @RequestMapping(prefix+"/product.html")
    public ModelAndView HtmlProduct(@RequestParam(value="id",required = true) int id,Model model){
        ProductDao productDao=productService.getProductById(id);
        productDao=productService.flagProduct(productDao);
        model.addAttribute("product", productDao);
        return new ModelAndView("product");
    }
    @RequestMapping(prefix+"/groupbuy.html")
    public ModelAndView HtmlGroupBuy(HttpServletRequest request,Model model,@RequestParam(value="status",required = false) Integer status){
        if(status==null){
            status=-1;
        }
        HttpSession session=request.getSession();
        Integer userId=(Integer)session.getAttribute("userId");
        List<OrderDao> orderDaos=orderService.getOrders(userId,status);
        model.addAttribute("orders", orderDaos);
        return new ModelAndView("groupbuy");
    }

    @RequestMapping(prefix+"/orderdetail.html")
    public ModelAndView HtmlOrderDetail(HttpServletRequest request,Model model,@RequestParam(value="id",required = true) int id){
        HttpSession session=request.getSession();
        Integer userId=(Integer)session.getAttribute("userId");
        OrderDao orderDao=orderService.getOrderById(id);
        if(userId==orderDao.getUserId()) {
            model.addAttribute("order", orderDao);
        }
        return new ModelAndView("orderdetail");
    }
    @RequestMapping(value=prefix+"/verify/addBuyCar",method =RequestMethod.POST)
    @ResponseBody
    public String VerifyAddBuyCar(HttpServletRequest request,Model model,
                                        @RequestParam(value="productId",required = true) int productId,
                                        @RequestParam(value="attribute",required = true) String attribute,
                                        @RequestParam(value="qty",required = true) int qty){
        HttpSession session=request.getSession();
        int userId=(int)session.getAttribute("userId");
        int c=userService.createBuyCar(userId,productId,attribute,qty);
        if(c>0){
            return ApiResponse.Ok("操作成功",null);
        }
        return ApiResponse.Fail("操作失败");
    }
    @RequestMapping(value=prefix+"/verify/deleteBuyCar",method =RequestMethod.POST)
    @ResponseBody
    public String VerifyDeleteBuyCar(HttpServletRequest request,Model model,
                                  @RequestParam(value="id",required = true) int id
                                  ){
        HttpSession session=request.getSession();
        int userId=(int)session.getAttribute("userId");
        int c=userService.deleteBuyCar(userId,id);
        return ApiResponse.Ok("操作成功",null);
    }

    @RequestMapping(value=prefix+"/verify/reg",method =RequestMethod.POST)
    @ResponseBody
    public String VerifyReg(HttpServletRequest request,Model model,
                            @RequestParam(value="name",required = true) String name,
                            @RequestParam(value="phone",required =true) String phone,
                            @RequestParam(value="prov",required = true)String prov,
                            @RequestParam(value="city",required = true)String city,
                            @RequestParam(value="district",required = true)String district,
                            @RequestParam(value="address",required = true)String address
    ){
        HttpSession session=request.getSession();
        int userId=(int)session.getAttribute("userId");
        int c=userService.reg(userId,name,phone,prov,city,district,address);
        return ApiResponse.Ok("操作成功",null);
    }

    @RequestMapping(value=prefix+"/verify/buy",method =RequestMethod.POST)
    @ResponseBody
    public String VerifyBuy(HttpServletRequest request,Model model,
                            @RequestParam(value="obj",required = true) String objStr
    ){
        JSONObject json = new JSONObject().parseObject(objStr);
        List<OrderDetailDao> detailDaos=new ArrayList<OrderDetailDao>();
        HttpSession session=request.getSession();
        int userId=(int)session.getAttribute("userId");
        UserDao userDao=userService.getUser(userId);
        if(userDao.getPhone()==null||userDao.getPhone().equalsIgnoreCase("")){
            return ApiResponse.Msg(-3,"没有登记收货信息",null);
        }
        double total=0.00;
        boolean area=false;
        for(String key :json.keySet()){
            String value=json.getString(key);
            int qty=Integer.parseInt(value);
            BuyCarDao dao=userService.getBuyCarById(Integer.parseInt(key));
            int productId=dao.getProduct().getId();
            if(productId==3){
                String prov=userDao.getProvince();
                String city=userDao.getCity();
                if(!prov.contains("广东")&&!prov.contains("广西")&&(prov.contains("湖南")&&(!city.contains("郴州")&&!city.contains("永州")))){
                    return ApiResponse.Fail("套餐三只限广东、广西、湖南郴州、湖南永州地区。");
                }
            }
            double price=dao.getProduct().getPrice();
            total+=qty*price;
            OrderDetailDao detailDao=new OrderDetailDao();
            detailDao.setAttribute(dao.getAttrStr());
            detailDao.setImg(dao.getProduct().getImg());
            detailDao.setName(dao.getProduct().getName());
            detailDao.setPrice(price);
            detailDao.setQty(qty);
            detailDaos.add(detailDao);
        }
        if(total<5000&&!session.getAttribute("openid").equals("oclyy1Y4GbNp6QDJU6Si_PuGMCyc")&&!session.getAttribute("openid").equals("oclyy1dFk66r5d-bsrEmF0VnZLWs")){
            return ApiResponse.Fail("下单最低5000起");
        }

        OrderDao orderDao=new OrderDao();
        orderDao.setName(userDao.getName());
        orderDao.setPhone(userDao.getPhone());
        orderDao.setAddress(userDao.getAddress());
        orderDao.setCity(userDao.getCity());
        orderDao.setDist(userDao.getDist());
        orderDao.setOpenid(userDao.getOpenid());
        orderDao.setProvince(userDao.getProvince());
        orderDao.setStatus(0);
        orderDao.setTotal(total);
        orderDao.setUserId(userId);
        orderDao.setNumber(orderService.createNumber());
        String createMsg=orderService.createOrder(orderDao,detailDaos);
        JSONObject jsonObject=JSON.parseObject(createMsg);
        if(jsonObject.getInteger("code")==ApiResponse.SUCCESS_CODE){
            int orderId=jsonObject.getInteger("data");
            Weixin wx=new Weixin();
            try {
                WXPay wxPay=new WXPay(wx,Weixin.NOTIfFU_URL);
                Map<String,String> dataMap=new HashMap<String, String>();
                dataMap.put("appid",Weixin.APPID);
                dataMap.put("mch_id",Weixin.MCHID);
                dataMap.put("body","温氏乳业-团购套餐");
                dataMap.put("attach","温氏乳业团购");
                dataMap.put("out_trade_no",orderDao.getNumber());
                long t=Math.round(total*100);
                String money=String.valueOf(t);
                dataMap.put("total_fee",money);
                dataMap.put("spbill_create_ip",InetAddress.getLocalHost().getHostAddress());
                dataMap.put("trade_type","JSAPI");
                dataMap.put("openid",(String)session.getAttribute("openid"));
                dataMap.put("device_info","WEB");
                Map<String,String> results=wxPay.unifiedOrder(dataMap);
                String time=String.valueOf(WXPayUtil.getCurrentTimestamp());
                String  nonceStr=WXPayUtil.generateNonceStr();
                if(results.get("return_code").equalsIgnoreCase("SUCCESS")){
                    JSONObject obj=new JSONObject();
                    obj.put("appId",Weixin.APPID);
                    obj.put("timeStamp",time);
                    obj.put("nonceStr",nonceStr);
                    obj.put("package","prepay_id="+results.get("prepay_id"));
//                    obj.put("signType","MD5");
                    obj.put("signType","HMAC-SHA256");
                    Map<String,String> signMap=new HashMap<String, String>();
                    signMap.put("appId",Weixin.APPID);
//                    signMap.put("mch_id",Weixin.MCHID);
                    signMap.put("package","prepay_id="+results.get("prepay_id"));
                    signMap.put("signType","HMAC-SHA256");
                    signMap.put("nonceStr",nonceStr);
                    signMap.put("timeStamp",time);
//                    obj.put("paySign",results.get("sign"));
//                    String xmlStr=WXPayUtil.mapToXml(signMap);
                    obj.put("paySign",WXPayUtil.generateSignature(signMap,Weixin.KEY, WXPayConstants.SignType.HMACSHA256));
                    obj.put("my_orderId",orderId);
                    String payInfo=obj.toJSONString();
                    return ApiResponse.Ok("操作成功",obj);
                }else {
                    return ApiResponse.Fail(results.get("return_code")+":"+results.get("return_msg"));
                }
            } catch (Exception e) {
                return ApiResponse.Fail(e.getMessage());
            }
//            return ApiResponse.Ok("操作成功",null);
        }else{
            return ApiResponse.Fail(createMsg);
        }
    }

    @RequestMapping(value=prefix+"/verify/test",method =RequestMethod.GET)
    @ResponseBody
    public String test(HttpServletRequest request,Model model,
                                     @RequestParam(value="id",required = false) int id
    ){
        return ApiResponse.Ok("操作成功",null);
    }


//    @RequestMapping("/verify/index.html")
//    public ModelAndView fff(Model model,HttpServletRequest request){
//        String openid="chy";
//        HttpSession session=request.getSession();
//        session.setAttribute("openid",openid);
//        return new ModelAndView("redirect:/index.html");
//    }
}
